// https://uniapp.dcloud.net.cn/tutorial/platform.html
// APP-PLUS App
// APP-PLUS-NVUE或APP-NVUE App nvue 页面
// APP-ANDROID App Android 平台 仅限 uts文件
// APP-IOS App iOS 平台 仅限 uts文件
// H5 H5
// MP-WEIXIN 微信小程序
// MP-ALIPAY 支付宝小程序
// MP-BAIDU 百度小程序
// MP-TOUTIAO 抖音小程序
// MP-LARK 飞书小程序
// MP-QQ QQ小程序
// MP-KUAISHOU 快手小程序
// MP-JD 京东小程序
// MP-360 360小程序
// MP 微信小程序/支付宝小程序/百度小程序/抖音小程序/飞书小程序/QQ小程序/360小程序
// QUICKAPP-WEBVIEW 快应用通用(包含联盟、华为)
// QUICKAPP-WEBVIEW-UNION 快应用联盟
// QUICKAPP-WEBVIEW-HUAWEI 快应用华为
//



import dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc'

export const getPlatform = () => {
  let platForm
  // #ifdef APP-PLUS || APP-NVUE || APP-PLUS-NVUE
  platForm = 'APP'
  // #endif
  // #ifdef H5
  platForm = 'H5'
  // #endif
  // #ifdef MP-WEIXIN
  platForm = 'MP-WEIXIN'
  // #endif
  // #ifdef MP-ALIPAY
  platForm = 'MP-ALIPAY'
  // #endif
  // #ifdef MP-BAIDU
  platForm = 'MP-BAIDU'
  // #endif
  // #ifdef MP-TOUTIAO
  platForm = 'MP-TOUTIAO'
  // #endif
  // #ifdef MP-LARK
  platForm = 'MP-LARK'
  // #endif
  // #ifdef MP-QQ
  platForm = 'MP-QQ'
  // #endif
  // #ifdef MP-KUAISHOU
  platForm = 'MP-KUAISHOU'
  // #endif
  // #ifdef MPJD-
  platForm = 'MP-JD'
  // #endif
  // #ifdef MP-360
  platForm = 'MP-360'
  // #endif
  // #ifdef QUICKAPP-WEBVIEW
  platForm = 'QUICKAPP-WEBVIEW'
  // #endif
  // #ifdef QUICKAPP-WEBVIEW-UNION
  platForm = 'QUICKAPP-WEBVIEW-UNION'
  // #endif
  // #ifdef QUICKAPP-WEBVIEW-HUAWEI
  platForm = 'QUICKAPP-WEBVIEW-HUAWEI'
  // #endif
  return platForm
}
//判断ios和安卓
export const checkDeviceType = () => {
  return new Promise((resolve, reject) => {
    uni.getSystemInfo({
      success: (res) => {
        const platform = res.platform.toLowerCase()
        if (platform === 'ios') {
          resolve('iOS')
        } else if (platform === 'android') {
          resolve('Android')
        } else {
          reject('Unknown')
        }
      },
      fail: (err) => {
        reject(err)
      },
    })
  })
}
// 清除对象中值不存在的键
export const objectNilClean = (obj) => {
  const newObj = clone(obj)
  delete newObj._X_ROW_KEY
  Object.keys(newObj).forEach(e => {
    if (isNil(newObj[e])) {
      delete newObj[e]
    }
  })
  return newObj
}
// 清除对象中值为空的键
export const objectClean = (obj) => {
  const newObj = clone(obj)
  delete newObj._X_ROW_KEY
  Object.keys(newObj).forEach(e => {
    if (isNilOrEmpty(newObj[e])) {
      delete newObj[e]
    }
  })
  return newObj
}

export const parseTableName = (tableName = '') => {
  let schema
  let table = tableName
  if (tableName.includes('.') && tableName.split('.').length > 1) {
    schema = tableName.split('.')[0]
    table = tableName.split('.')[1]
  }
  return { schema, table }
}

// 时间的区分 (超过24小时以多少天显示,不超过24小时,以多少小时前显示出来)
export const formatDayTime = (time1) => {
  const now = new Date()
  const time = time1.getTime()
  const diff = now - time
  const oneHour = 60 * 60 * 1000
  const oneDay = 24 * oneHour

  if (diff >= oneDay) {
    // 超过 24 小时，以日显示
    const days = Math.floor(diff / oneDay)
    return `${days} 天前`
  } else if (diff >= oneHour) {
    // 超过一小时不超过 24 小时，以小时显示
    const hours = Math.floor(diff / oneHour)
    return `${hours} 小时前`
  } else {
    // 不超过一小时，以分钟显示
    const minutes = Math.floor(diff / (60 * 1000))
    return `${minutes} 分钟前`
  }
}
//数组扁平化（树状数组转普通数组）
export const treeToFlat = (arr, str = 'children') => {
  return arr.reduce((result, item) => {
    return result.concat(item, (Array.isArray(item[str]) ? treeToFlat(item[str]) : []))
  }, [])
}

// Tab页中的路径，请根据自己项目实际情况进行修改
const tabBarUrl = ['/pages/index', '/pages/health', '/pages/mall', '/pages/mine', '/pages/square']
//路由跳转
export function navTo(url, callback = undefined) {
  let newUrl = url
  if (url[0] === '/') { // 过滤首位的 /
    newUrl = url.substring(1)
  }
  const pathname = newUrl.split('?')[0]
  const params = newUrl.split('?')[1]
  const page = getCurrentPages()
  const index = page.findIndex(item => item.route === pathname)
  // 如果是Tab中的链接，直接跳转
  if (tabBarUrl.includes(pathname)) {
    uni.switchTab({
      url,
      success: () => {
        callback && callback()
      },
    })
    return
  }
  if (index !== -1) { // 在页面栈中找到时
    const step = page.length - 1 - index
    if (step === 0) {
      uni.redirectTo({
        url,
        success: () => {
          callback && callback()
        },
      })
    } else {
      if (params) {
        uni.redirectTo({
          url,
          success: () => {
            callback && callback()
          },
        })
        return
      }
      uni.navigateBack({ delta: step })
      callback && callback()
    }
    return
  }
  // 否则就直接跳转
  uni.navigateTo({
    url,
    success: () => {
      callback && callback()
    },
  })
}
//跳转tabbar页面，并刷新数据
export function reLanchTo(url) {
  uni.reLaunch({ url })
}
//返回上一级页面
export const goBack = () => {
  uni.navigateBack({
    delta: 1,
  })
}
//是否为json串
export const isJSON = (str) => {
  if (typeof str == 'string') {
    try {
      let obj = JSON.parse(str)
      if (typeof obj == 'object' && obj) {
        return true
      } else {
        return false
      }

    } catch (e) {
      return false
    }
  }
}

export const oneToTwoArray = (list) => {
  let arrayTwo = Object.values(list.reduce((res, item) => {
    res[item.id] ? res[item.id].push(item) : res[item.id] = [item]
    return res
  }, {}))
  let data = []
  arrayTwo.forEach((nowItem) => {
    let obj = {}
    obj.title = nowItem[0].content
    obj.options = nowItem
    data.push(obj)
  })
  return data
}

//时间处理

export const formatMsgTime = (timespan) => {
  let timeSpan = timespan.replace (/-/g, '/') //兼容ios 8
  let dateTime = new Date(timeSpan) // 将传进来的字符串或者毫秒转为标准时间
  let year = dateTime.getFullYear()
  let month = dateTime.getMonth() + 1
  let day = dateTime.getDate()
  let hour = dateTime.getHours()
  let minute = dateTime.getMinutes()
  // var second = dateTime.getSeconds()
  let millisecond = dateTime.getTime() // 将当前编辑的时间转换为毫秒
  let now = new Date() // 获取本机当前的时间
  let nowNew = now.getTime() // 将本机的时间转换为毫秒
  let milliseconds = 0
  let timeSpanStr
  milliseconds = nowNew - millisecond
  if (milliseconds <= 1000 * 60 * 1) { // 小于一分钟展示为刚刚
    timeSpanStr = '一分钟前'
  } else if (1000 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60) { // 大于一分钟小于一小时展示为分钟
    timeSpanStr = `${Math.round((milliseconds / (1000 * 60)))}分钟前`
  } else if (1000 * 60 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24) { // 大于一小时小于一天展示为小时
    timeSpanStr = `${Math.round(milliseconds / (1000 * 60 * 60))}小时前`
  } else if (1000 * 60 * 60 * 24 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24 * 15) { // 大于一天小于十五天展示位天
    timeSpanStr = `${Math.round(milliseconds / (1000 * 60 * 60 * 24))}天前`
  } else if (milliseconds > 1000 * 60 * 60 * 24 * 15 && year === now.getFullYear()) {
    timeSpanStr = `${month}-${day}` //超过一个月
  } else {
    timeSpanStr = `${year}-${month}-${day}` //超过一年
  }
  return timeSpanStr
}
// 健康页面返回跳转
export const goHealthBack = () => {
  navTo('/pages-health/healthProgramme')
}

//处理距离转换
export const formatDistance = (distance) => {
  if (distance >= 1000) {
    const kilometers = Math.round((distance / 1000) * 100) / 100
    return `${kilometers}km`
  } else {
    return `${Math.round(distance * 100) / 100}m`
  }
}

export const formatTime = (date, type) => {
  dayjs.extend(utc)
  if (!date) {
    return
  }
  return dayjs(date).utc().local().format(type)
}

//html 转换json [type:'text',content:'']
export const parseHTML = (html) => {
  const textRegex = /<(?!img)[^>]*>(.*?)<\/[^>]+>/g //匹配img以外的标签
  const imageRegex = /<img[^>]*src="([^"]+)"[^>]*>/g
  const textMatch = html.match(textRegex)
  const imageMatch = html.match(imageRegex) || [] // 添加判断，如果为null则赋值为空数组
  const textArray = textMatch.map((match) => {
    const text = match.replace(/<[^>]+>/g, '')
    const tag = match.match(/<([^>]+)/)[1]
    return { type: 'text', content: text, tag }
  })
  const imageArray = imageMatch.map((match, index) => {
    const src = match.match(/src="([^"]+)"/)[1]
    return { type: 'img', content: src, index, tag: 'img' }
  })
  const resultArray = []
  let textIndex = 0
  let imageIndex = 0
  while (textIndex < textArray.length || imageIndex < imageArray.length) {
    if (textIndex < textArray.length) {
      resultArray.push(textArray[textIndex])
      textIndex++
    }
    if (imageIndex < imageArray.length) {
      resultArray.push(imageArray[imageIndex])
      imageIndex++
    }
  }
  return resultArray.filter((item) => item.content !== '')
}
//把json转换Dom,注:此转换把文字只转换成p标签，图片转换img
export const parseDOM = (htmlJSON) => {
  try {
    const data = htmlJSON
    let result = ''
    for (const item of data) {
      if (item.type === 'text') {
        result += `<p>${item.content}</p >`
      } else if (item.type === 'img') {
        result += `< img src="${item.content}" alt="Image">`
      }
    }
    return result
  } catch (error) {
    console.error('转换失败:', error)
    return ''
  }
}

export const checkLocationPermission = () => {
  return new Promise((resolve, reject) => {
    uni.getSetting({
      success(res) {
        if (res.authSetting['scope.userLocation']) {
          resolve(true)
        } else {
          resolve(false)
        }
      },
      fail(err) {
        reject(err)
      },
    })
  })
}

